package org.nnxy.foodboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nnxy.foodboot.entity.UserBrowseHistory;
import org.nnxy.foodboot.service.UserBrowseHistoryService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户浏览历史控制器
 */
@RestController
@RequestMapping("/api/user/browse")
@RequiredArgsConstructor
@Slf4j
public class UserBrowseHistoryController {

    private final UserBrowseHistoryService userBrowseHistoryService;

    /**
     * 记录用户浏览历史
     */
    @PostMapping("/record")
    public Map<String, Object> recordBrowse(@RequestBody Map<String, Object> params) {
        Integer userId = null;
        Integer recipeId = null;
        Integer browseDuration = null;
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (params.get("userId") != null) {
                userId = Integer.valueOf(params.get("userId").toString());
            }
            
            if (params.get("recipeId") != null) {
                recipeId = Integer.valueOf(params.get("recipeId").toString());
            }
            
            if (params.get("browseDuration") != null) {
                browseDuration = Integer.valueOf(params.get("browseDuration").toString());
            }
            
            if (userId == null || recipeId == null) {
                result.put("code", 400);
                result.put("message", "用户ID和食谱ID不能为空");
                return result;
            }
            
            log.info("记录用户浏览历史: userId={}, recipeId={}, duration={}", userId, recipeId, browseDuration);
            
            UserBrowseHistory history = userBrowseHistoryService.addBrowseHistoryWithReturn(userId, recipeId, browseDuration);
            
            if (history != null) {
                result.put("code", 200);
                result.put("message", "记录成功");
                result.put("data", history);
            } else {
                result.put("code", 500);
                result.put("message", "记录失败");
            }
        } catch (NumberFormatException e) {
            log.error("参数类型错误", e);
            result.put("code", 400);
            result.put("message", "参数类型错误：" + e.getMessage());
        } catch (Exception e) {
            log.error("记录浏览历史异常", e);
            result.put("code", 500);
            result.put("message", "服务器错误：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 更新浏览时长
     */
    @PutMapping("/duration/{id}")
    public Map<String, Object> updateBrowseDuration(@PathVariable Integer id, @RequestBody Map<String, Object> params) {
        Integer browseDuration = null;
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (params.get("browseDuration") != null) {
                browseDuration = Integer.valueOf(params.get("browseDuration").toString());
            }
            
            if (id == null || browseDuration == null) {
                result.put("code", 400);
                result.put("message", "ID和浏览时长不能为空");
                return result;
            }
            
            log.info("更新浏览时长: id={}, duration={}", id, browseDuration);
            
            boolean success = userBrowseHistoryService.updateBrowseDuration(id, browseDuration);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "更新成功");
            } else {
                result.put("code", 500);
                result.put("message", "更新失败");
            }
        } catch (NumberFormatException e) {
            log.error("参数类型错误", e);
            result.put("code", 400);
            result.put("message", "参数类型错误：" + e.getMessage());
        } catch (Exception e) {
            log.error("更新浏览时长异常", e);
            result.put("code", 500);
            result.put("message", "服务器错误：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取用户浏览历史列表
     */
    @GetMapping("/list")
    public Map<String, Object> getBrowseHistoryList(@RequestParam Integer userId, @RequestParam(defaultValue = "10") Integer limit) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (userId == null) {
                result.put("code", 400);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            log.info("获取用户浏览历史列表: userId={}, limit={}", userId, limit);
            
            List<UserBrowseHistory> historyList = userBrowseHistoryService.getUserBrowseHistoryList(userId, limit);
            
            result.put("code", 200);
            result.put("data", historyList);
        } catch (Exception e) {
            log.error("获取浏览历史列表异常", e);
            result.put("code", 500);
            result.put("message", "服务器错误：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 分页获取用户浏览历史
     */
    @GetMapping("/page")
    public Map<String, Object> getBrowseHistoryPage(
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (userId == null) {
                result.put("code", 400);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            log.info("分页获取用户浏览历史: userId={}, current={}, size={}", userId, current, size);
            
            Page<UserBrowseHistory> page = userBrowseHistoryService.getUserBrowseHistoryPage(new Page<>(current, size), userId);
            
            result.put("code", 200);
            result.put("data", page);
        } catch (Exception e) {
            log.error("分页获取浏览历史异常", e);
            result.put("code", 500);
            result.put("message", "服务器错误：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除指定浏览记录
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteBrowseHistory(@PathVariable Integer id, @RequestParam Integer userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (id == null || userId == null) {
                result.put("code", 400);
                result.put("message", "ID和用户ID不能为空");
                return result;
            }
            
            log.info("删除浏览记录: id={}, userId={}", id, userId);
            
            boolean success = userBrowseHistoryService.deleteUserBrowseHistory(id, userId);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            log.error("删除浏览记录异常", e);
            result.put("code", 500);
            result.put("message", "服务器错误：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 清空浏览记录
     */
    @DeleteMapping("/clear")
    public Map<String, Object> clearBrowseHistory(@RequestParam Integer userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (userId == null) {
                result.put("code", 400);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            log.info("清空浏览记录: userId={}", userId);
            
            boolean success = userBrowseHistoryService.clearUserBrowseHistory(userId);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "清空成功");
            } else {
                result.put("code", 500);
                result.put("message", "清空失败");
            }
        } catch (Exception e) {
            log.error("清空浏览记录异常", e);
            result.put("code", 500);
            result.put("message", "服务器错误：" + e.getMessage());
        }
        
        return result;
    }
} 